package com.mingliqiye.minecraft.enchantment.conflict.common;

import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WebConfigCore {

    private Javalin javalin;
    private final int port;
    private final ConfigManager configManager;
    private final WebConfigCoreMeMethod webConfigCoreMeMethod;
    private final WebApis webApis;
    private boolean started = false;

    public WebConfigCore(ConfigManager configManager, WebConfigCoreMeMethod webConfigCoreMeMethod) {
        this.configManager = configManager;
        this.webConfigCoreMeMethod = webConfigCoreMeMethod;
        port = getProt();
        webApis = new WebApis(configManager, webConfigCoreMeMethod);
    }

    public void start() {
        javalin = Javalin.create((config) -> {
            config.staticFiles.add((staticFiles) -> {
                staticFiles.directory = "/assets/enchantmentdoesnotconflict/web/assets";
                staticFiles.location = Location.CLASSPATH;
                staticFiles.hostedPath = "/assets";
            });
        });
        javalin.get("/", (ctx) -> {
            ctx.html(DefConfig.getResByString("/assets/enchantmentdoesnotconflict/web/index.html"));
        });
        webApis.loadApis(javalin);
        javalin.start(port);
        started = true;
    }

    public void stop() {
        if (started) {
            javalin.stop();
        }
    }

    public int getProt() {
        if (webConfigCoreMeMethod.getDevMode()) {
            return 15563;
        }
        try (ServerSocket s = new ServerSocket(0)) {
            return s.getLocalPort();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 15563;
    }

    public String getLocalUrl() {
        return "http://localhost:" + port;
    }

    public void openWeb() {
        WebOpener.openURL(getLocalUrl());
    }
}
